package com.yc.vote.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.mybatis.util.RequestParamUtil;
import com.yc.vote.bean.Topics;
import com.yc.vote.bean.UserInfo;
import com.yc.vote.dao.impl.TopicsServiceImpl;
import com.yc.vote.service.ITopicsService;
@WebServlet("/topic/*")
public class TopicsController extends BaseCotroller{
	private static final long serialVersionUID = 247980361132654990L;

	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Object obj = request.getSession().getAttribute("currentLoginUser");
		if(obj == null) {
			this.send(response, 600,"未登录");
			return;
		}
		UserInfo uf = (UserInfo) obj;
		Topics tp = RequestParamUtil.getParams(request, Topics.class);
		tp.setUsid(uf.getUsid());
		ITopicsService topicsService = new TopicsServiceImpl();
		int result = topicsService.add(tp);
		if(result >0) {
			this.send(response, 200,"成功");
			return;
		}
		this.send(response, 500,"失败");
	}
	/**
	 * 查询所有投票主题信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void finds(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ITopicsService topicsService = new TopicsServiceImpl();
		List<Topics> list = topicsService.findAll();
		System.out.println("list==@@"+list);
		if(list != null && !list.isEmpty()) {
			this.send(response, 200,list);
			return ;
		}
		this.send(response, 600,"暂无数据");
	}
	/**
	 * 根据主题编号查询主题
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void findByTid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String tid = request.getParameter("tid");
		System.out.println("tid="+tid);
		ITopicsService topicsService = new TopicsServiceImpl();
		Topics topics = topicsService.findByTid(tid);
		System.out.println("topics="+topics);
		if(topics != null) {
			this.send(response, 200,topics);
			return;
		}
		this.send(response, 600,"暂无数据");
	}
	
	public void vote(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Object obj = request.getSession().getAttribute("currentLoginUser");
		if(obj == null) {
			this.send(response, 600,"未登录");
			return;
		}
		UserInfo uf = (UserInfo) obj;
		String tid = request.getParameter("tid");
		String iids = request.getParameter("iids");
		
		ITopicsService topicsService = new TopicsServiceImpl();
		int result = topicsService.update(tid, uf.getUsid(), iids);
		if(result >0) {
			this.send(response, 200,"成功");
			return;
		}
		this.send(response, 500,"失败");
	}
}
